<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="5" :xs="10">
        <!--仓库-->
        <div class="head-container">
          <el-input v-model="storeName" placeholder="请输入仓库名称" clearable size="small" prefix-icon="el-icon-search"
            style="margin-bottom: 20px" />
        </div>
        <div class="head-container">
          <el-tree :data="storeOptions" :props="defaultProps" :expand-on-click-node="false"
            :filter-node-method="filterNode" ref="tree" default-expand-all @node-click="handleNodeClick" />
        </div>
      </el-col>
      <el-col :span="19" :xs="14">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <!-- <el-form-item label="部门" prop="deptId">
            <treeselect v-model="queryParams.deptId" :options="deptOptions" :show-count="true" placeholder="机构"
              style="width: 260px" size="small" />
          </el-form-item> -->

          <el-form-item label="经办人" prop="operator">
            <el-select v-model="queryParams.operator" placeholder="请选择经办人" style="width: 100%">
              <el-option v-for="item in userOptions" :key="item.userId" :label="item.nickName" :value="item.userName" />
            </el-select>
          </el-form-item>
          <el-form-item label="类型" prop="type">
            <el-select v-model="queryParams.type" placeholder="请选择类型" clearable size="small">
              <el-option v-for="dict in dict.type.wms_inventory_log_type" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
              <el-option v-for="dict in dict.type.sys_common_status" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
 -->
         <!-- <el-form-item label="创建人" prop="createBy">
            <el-select v-model="queryParams.createBy" placeholder="请选择经办人" style="width: 100%">
              <el-option v-for="item in userOptions" :key="item.userId" :label="item.nickName" :value="item.userName" />
            </el-select>
          </el-form-item> -->


          <el-form-item label="创建时间">
            <el-date-picker v-model="daterangeCreateTime" size="small" style="width: 240px" value-format="yyyy-MM-dd"
              type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="inventoryLogList" @selection-change="handleSelectionChange" border stripe>
          <el-table-column type="index" width="55" align="center" fixed="left"/>
          <!-- <el-table-column label="记录id" align="center" prop="id" v-if="true"/> -->
          <el-table-column label="物品编号" prop="pno" min-width="260" fixed="left"/>
          <el-table-column label="物品名称" prop="name" min-width="160"/>
          <el-table-column label="仓库" prop="storeName" min-width="260"/>
          <el-table-column label="类型" align="center" prop="type" fixed="right">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.wms_inventory_log_type" :value="scope.row.type" />
            </template>
          </el-table-column>
          <el-table-column label="变动前" align="center" prop="befores" fixed="right"/>
          <el-table-column label="变动" align="center" prop="nums" fixed="right"/>
          <el-table-column label="变动后" align="center" prop="afters" fixed="right"/>

          <el-table-column label="部门" prop="deptName"  min-width="260"/>
          <!-- <el-table-column label="事件ID" align="center" prop="referId" /> -->
          <el-table-column label="经办人" prop="operator"  min-width="220"/>
          <el-table-column label="原因" prop="memo" />
          <el-table-column label="状态" align="center" prop="status">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_common_status" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column label="创建人" prop="createBy" />
          <el-table-column label="创建时间" align="center" prop="createTime" width="180" fixed="right">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="remark" />
          <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wms:inventoryLog:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wms:inventoryLog:remove']"
          >删除</el-button>
        </template>
      </el-table-column> -->
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
          @pagination="getList" />
      </el-col>
    </el-row>

  </div>
</template>

<script>
  import {
    listInventoryLog,
    getInventoryLog,
    delInventoryLog,
    addInventoryLog,
    updateInventoryLog
  } from "@/api/wms/inventoryLog";
  import {
    listStore,
    storeTreeselect
  } from "@/api/wms/store";
  import {
    treeselect
  } from "@/api/system/dept";
  import {
    listUser
  } from "@/api/system/user"
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  export default {
    name: "InventoryLog",
    dicts: ['sys_common_status', 'wms_inventory_log_type'],
    components: {
      Treeselect
    },
    data() {
      return {
        // 按钮loading
        buttonLoading: false,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 库存记录表格数据
        inventoryLogList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 备注时间范围
        daterangeCreateTime: [],
        // 备注时间范围
        daterangeUpdateTime: [],
        storeOptions: [],
        storeTree: [],
        storeName: undefined,
        deptOptions: [],
        defaultProps: {
          children: "children",
          label: "label"
        },
        userOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          stockId: undefined,
          storeId: undefined,
          type: undefined,
          referId: undefined,
          operator: undefined,
          status: undefined,
          deptId: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          delFlag: undefined
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          stockId: [{
            required: true,
            message: "库存id不能为空",
            trigger: "blur"
          }],
          storeId: [{
            required: true,
            message: "仓库id不能为空",
            trigger: "blur"
          }],
          befores: [{
            required: true,
            message: "变动前数量不能为空",
            trigger: "blur"
          }],
          nums: [{
            required: true,
            message: "变动数量不能为空",
            trigger: "blur"
          }],
          afters: [{
            required: true,
            message: "变动后数量不能为空",
            trigger: "blur"
          }],
          type: [{
            required: true,
            message: "类型不能为空",
            trigger: "change"
          }],
          operator: [{
            required: true,
            message: "经办人不能为空",
            trigger: "blur"
          }],
        }
      };
    },
    watch: {
      storeName(val) {
        this.$refs.tree.filter(val);
      },
      // 'queryParams.deptId': {
      //   handler(newVal, oldVal) {
      //     this.deptChange();
      //   },
      //   deep: true,
      //   immediate: true
      // }
    },
    created() {
      this.getList();
      this.getStoreTreeselect();
      this.getTreeselect();
    },
    methods: {
      /** 查询库存记录列表 */
      getList() {
        this.loading = true;
        this.queryParams.params = {};
        if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
          this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
          this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
        }
        if (null != this.daterangeUpdateTime && '' != this.daterangeUpdateTime) {
          this.queryParams.params["beginUpdateTime"] = this.daterangeUpdateTime[0];
          this.queryParams.params["endUpdateTime"] = this.daterangeUpdateTime[1];
        }
        listInventoryLog(this.queryParams).then(response => {
          this.inventoryLogList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      /** 查询分类下拉树结构 */
      getStoreTreeselect() {
        storeTreeselect().then(response => {
          this.storeOptions = response.data;
        });
      },
      /** 查询部门下拉树结构 */
      getTreeselect() {
        treeselect().then(response => {
          this.deptOptions = response.data;
        });
      },
      deptChange() {
        this.getList();
        this.getUsers();
      },
      getUsers() {
        listUser({
          'userType': 'sys_user',
          'deptId': this.queryParams.deptId
        }).then(response => {
          this.userOptions = response.rows
        })
      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      // 节点单击事件
      handleNodeClick(data) {
        this.queryParams.storeId = data.id;
        this.handleQuery();
      },
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.id,
          label: node.name,
          children: node.children
        };
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          stockId: undefined,
          storeId: undefined,
          befores: undefined,
          nums: undefined,
          afters: undefined,
          type: undefined,
          referId: undefined,
          operator: undefined,
          memo: undefined,
          status: undefined,
          deptId: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          remark: undefined,
          delFlag: undefined
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.daterangeCreateTime = [];
        this.daterangeUpdateTime = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加库存记录";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.loading = true;
        this.reset();
        const id = row.id || this.ids
        getInventoryLog(id).then(response => {
          this.loading = false;
          this.form = response.data;
          this.open = true;
          this.title = "修改库存记录";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.buttonLoading = true;
            if (this.form.id != null) {
              updateInventoryLog(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            } else {
              addInventoryLog(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除库存记录编号为"' + ids + '"的数据项？').then(() => {
          this.loading = true;
          return delInventoryLog(ids);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).finally(() => {
          this.loading = false;
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('wms/inventoryLog/export', {
          ...this.queryParams
        }, `inventoryLog_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
